import { Component, Provide, Vue } from 'vue-property-decorator'

@Component
export default class extends Vue {
  // ++++++++++ model ++++++++++
  loading = false

  // ++++++++++ props ++++++++++
  // ++++++++++ data ++++++++++
  data: Array<any> = []
  queryData!: (params?: any) => Promise<Array<any> | any>
  queryPage!: (params?: any) => Promise<Array<any> | any>
  pagination: { total: number, page: number, pageSize: number } = { total: 0, page: 1, pageSize: 10 }
  handleFunc: { save?: (params: any) => any, update?: (params: any) => any, remove?: (params: any) => any } | null = null
  searchParams = {} as any
  selection: Array<any> = [] // 选择的数据

  // ++++++++++ computed ++++++++++
  get params() {
    return {
      page: this.pagination.page - 1,
      pageSize: 10,
      ...this.searchParams,
    }
  }

  // 是否禁用按钮 selection 只选中一个值
  get isDisabled() {
    return this.selection.length != 1
  }

  @Provide('dataProvide') dataProvide() {
    return this
  }

  // ++++++++++ methods normal ++++++++++
  async once() { }

  async loadData() {
    if (this.queryData instanceof Function) {
      this.data = await this.queryData(this.params)
    } else if (this.queryPage instanceof Function) {
      const { list, total } = await this.queryPage(this.params)

      this.data = list
      this.pagination.total = total
    } else {
      throw new Error('请提供queryData或者queryPage方法')
    }
  }

  async load(page?: number) {
    if (page) {
      this.pagination.page = page
    }
    try {
      this.loading = true
      await this.loadData()
    } finally {
      this.loading = false
    }
  }

  /**
   * 添加数据
   * @param params 参数
   */
  async handleAdd(params: any) {
    const add = this.handleFunc?.save ?? null

    if (!add) {
      return
    }
    await add(params)
    await this.load(1)
  }

  /**
   * 修改数据
   * @param params 参数
   */
  async handleUpdate(params: any) {
    console.log(1)
    const update = this.handleFunc?.update ?? null

    if (!update) {
      return
    }
    try {
      await update(params)
      await this.load(1)
      this.$message.success('已修改')
    } catch {
      //
    }
  }

  /**
   * 删除数据
   * @param params 参数
   */
  async handleRemove(params: any) {
    const remove = this.handleFunc?.remove

    if (remove) {
      await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        await remove(params)
        await this.load()
        this.$message.success('已删除')
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    } else {
      throw new Error('提供Remove方法')
    }
  }

  // ++++++++++ methods event ++++++++++
  // ++++++++++ Lifecycle Hooks ++++++++++
  async mounted() {
    await this.once()
    await this.load()
  }

  // ++++++++++ watch ++++++++++
}
